package com.piece.core.log.config;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * 审计日志信息线程
 */
@Slf4j
public class AuditLogContextHolder {

    /**
     * 支持父子线程之间的数据传递
     */
    private static final ThreadLocal<StandardEvaluationContext> CONTEXT = new TransmittableThreadLocal<>();

    public static final String CONTEXT_KEY_NAME_DIFF_RECORD = "_diff_record";

    public static StandardEvaluationContext getContext() {
        return null == CONTEXT.get() ? new StandardEvaluationContext(): CONTEXT.get();
    }

    public static StandardEvaluationContext getContext(BeanFactory beanFactory) {
        if (null == CONTEXT.get()) {
            StandardEvaluationContext context = new StandardEvaluationContext();
            context.setBeanResolver(new BeanFactoryResolver(beanFactory));
            return context;
        }
        return CONTEXT.get();
    }

    public static void putContext(StandardEvaluationContext context) {
        clearContext();
        CONTEXT.set(context);
    }

    public static void putVariable(String key, Object value) {
        StandardEvaluationContext context = getContext();
        context.setVariable(key, value);
        CONTEXT.set(context);
    }

    public static Object getVariable(String key) {
        return getContext().lookupVariable(key);
    }

    public static void clearContext() {
        CONTEXT.remove();
    }
}
